<template>
  <div>
    <!-- 工具栏 -->
    <div class="tools">
      <el-input
        v-model="queryRoleVo.roleName"
        style="width: 200px; margin-right: 15px"
        placeholder="角色名"
      ></el-input>
      <!-- status的初始值是谁就会默认选中谁 没设label的话选择后就会变成value1、2 -->
      <el-select v-model="status" placeholder="全部" style="margin-right: 15px">
        <el-option value="" label="全部">全部</el-option>
        <el-option value="1" label="有效">有效</el-option>
        <el-option value="0" label="无效">无效</el-option>
      </el-select>
      生效时间：
      <el-date-picker
        style="margin-right: 20px"
        v-model="queryCreateTime"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      >
      </el-date-picker>

      <el-button
        type="primary"
        icon="el-icon-search"
        @click="queryUser()"
        style="margin-right: 15px"
        >搜索</el-button
      >

      <!-- @click="addRoleFormVisible = true"打开嵌套的新增表单 -->
      <el-button
        class="addRoleButton"
        type="primary"
        @click="addRoleFormVisible = true"
        icon="el-icon-circle-plus-outline"
        >新增</el-button
      >
      <!-- 新增角色的对话框 -->
      <el-dialog title="添加角色" :visible.sync="addRoleFormVisible">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名" prop="roleName">
            <!-- *号 -->
            <el-col :span="11">
              <el-input v-model="ruleForm.roleName"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="生效日期" prop="effectTime" v-if="redio == 1">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.effectTime"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="redio">
              <el-radio :label="1">有效</el-radio>
              <el-radio :label="0">无效</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 只有当状态为无效时才可选 -->
          <el-form-item label="失效日期" prop="createTime" v-if="redio == 0">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.uneffectTime"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="ruleForm.note"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提 交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重 置</el-button>
            <el-button @click="addRoleFormVisible = false">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 编辑用户的对话框 -->
      <el-dialog
        title="编辑角色"
        :before-close="resetRuleForm"
        :visible.sync="editRoleFormVisible"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色编号">
            <el-col :span="11">
              <el-input v-model="ruleForm.roleId" disabled></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="角色名" prop="roleNameEdit">
            <el-col :span="11">
              <el-input v-model="ruleForm.roleName"></el-input>
            </el-col>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="redio">
              <el-radio :label="1">有效</el-radio>
              <el-radio :label="0">无效</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 只有当状态为无效时才可选 -->
          <el-form-item label="失效日期" prop="createTime" v-if="redio == 0">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.uneffectTime"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="生效日期" prop="effectTime" v-if="redio == 1">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="ruleForm.effectTime"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="ruleForm.note"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitEditRoleForm('ruleForm')"
              >提 交</el-button
            >
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button @click="resetRuleForm">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <br />
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="handleDelete"
        icon="el-icon-delete"
        >删除</el-button
      >
    </div>
    <!-- 分页表格 -->
    <div>
      <el-table
        height="410"
        ref="multipleTable"
        :data="roles"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="left" width="55">
        </el-table-column>
        <el-table-column label="序号" align="left" type="index" width="90">
          <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column
          prop="roleId"
          label="角色编码"
          show-overflow-tooltip
          align="left"
          width="90"
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          show-overflow-tooltip
          align="left"
          width="130"
        >
        </el-table-column>

        <el-table-column
          prop="note"
          label="描述"
          show-overflow-tooltip
          align="left"
          width="160"
        >
        </el-table-column>

        <el-table-column
          prop="effectTime"
          label="生效日期"
          show-overflow-tooltip
          align="left"
          width="130"
        >
        </el-table-column>
        <el-table-column
          prop="uneffectTime"
          align="left"
          label="失效日期"
          show-overflow-tooltip
          width="130"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          align="left"
          label="状态"
          show-overflow-tooltip
          width="120"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">无效</span>
            <span v-if="scope.row.status == 1">有效</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              align="left"
              type="primary"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              align="left"
              type="danger"
              @click="handleDelete2(scope.row)"
              >删除</el-button
            >

            <el-button
              size="mini"
              type="success"
              @click="handleRole(scope.$index, scope.row)"
              >设置角色权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页页码等 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[7, 15, 30, 60, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
// import {mapMutations} from "vuex";
export default {
  name: "RoleManage",
  data() {
    var validator1 = (rule, value, callback) => {
      if (value != "") {
        this.getRequest("/role/getOne?roleName=" + value).then((resp) => {
          if (resp.data != null) {
            callback(new Error("角色已存在"));
          } else {
            callback();
          }
        });
      }
    };
    return {
      // 工具栏中的日期搜索
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      status: "",
      createTime: "",
      // 初始为第一页
      currentPage: 1,
      // 总页数，从后台获取
      total: 1,
      // 每页的数量
      pageSize: 7,
      // 分页内容
      roles: [],
      // 被选中的用户数组
      roleSelected: [],
      // 模糊查询的用户名
      // 根据时间查询的数组
      queryCreateTime: [],
      queryRoleVo: {
        //模糊查询的对象
        roleName: "",
        beginTime: "",
        endTime: "",
        status: "",
      },
      // 添加角色对话框是否可见
      addRoleFormVisible: false,
      // 编辑角色的对话框是否可见
      editRoleFormVisible: false,

      //新增和编辑用户表单的状态
      redio: 1,
      // 新增用户和编辑用户表单里的值
      ruleForm: {
        roleName: "",
        effctTime: null,
        uneffectTime: null,
        status: "",
        note: "",
      },
      formLabelWidth: "120px",
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "角色名长度为2~100个英文字母或汉字组成",
            trigger: "blur",
          },
          {
            validator: validator1,
            trigger: "blur",
          },
        ],
      },
    };
  },

  // 钩子函数获取数据
  mounted() {
    this.initRoles();
    this.getNowTime();
  },
  methods: {
    //  复选框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 状态选择
    handleSelectionChange(val) {
      //提取选中用户的id
      this.roleSelected = val;
    },
    //    切换每页的数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.initRoles();
    },
    // 模糊查询用户
    queryUser() {
      //把选中的状态赋值给查询对象
      this.queryRoleVo.status = this.status;
      if (this.queryCreateTime) {
        //把选中的时间赋值给查询对象
        this.queryRoleVo.beginTime = this.queryCreateTime[0];
        this.queryRoleVo.endTime = this.queryCreateTime[1];
      } else {
        this.queryRoleVo.beginTime = "";
        this.queryRoleVo.endTime = "";
      }
      this.initRoles();
    },
    // 点击编写员工信息
    handleEdit(row) {
      // 把当前用户信息归到表单
      this.ruleForm.roleName = row.roleName;
      console.log(row.uneffectTime);
      this.ruleForm.roleId = row.roleId;
      this.redio = row.status;
      this.ruleForm.note = row.note;
      // 弹框可见
      this.editRoleFormVisible = true;
      // 如果有效就给无效的框设为当前时间反之就将有效的狂设为当前时间
      if (row.status == 1) {
        this.getNowTime();
        this.ruleForm.effectTime = row.effectTime;
      } else {
        this.getNowTime();
        this.ruleForm.uneffectTime = row.uneffectTime;
      }
    },
    // 编写完重置对话框的表单信息
    resetRuleForm() {
      this.ruleForm.roleName = "";
      this.ruleForm.roleId = "";
      this.ruleForm.note = "";
      this.editRoleFormVisible = false;
      this.redio = 1;
    },
    // 删除某一个员工
    handleDelete2(row) {
      // 提示是否永久删除该用户
      this.$confirm("是否要永久删除'" + row.roleName + "'角色的信息", "提示", {
        confirmButtonText: "是的",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteRequest("/role/delete?ids=" + row.roleId).then((resp) => {
           
              this.initRoles();
            
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除用户
    handleDelete() {
      if (this.roleSelected.length != 0) {
        // 提示是否永久删除该用户
        this.$confirm("删除后不可恢复，是否继续", "提示", {
          confirmButtonText: "继续",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let ids = "?";
            this.roleSelected.forEach((item) => {
              ids += "ids=" + item.roleId + "&";
            });
            this.deleteRequest("/role/delete" + ids).then((resp) => {
              
                this.initRoles();
              
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.$message.error("请选择要删除的角色");
      }
    },
    // 跳转页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initRoles();
    },
    // 初始化角色
    initRoles() {
      this.getRequest(
        "/role/selectAll?currentPage=" +
          this.currentPage +
          "&pageSize=" +
          this.pageSize,
        this.queryRoleVo
      ).then((resp) => {
        if (resp.data) {
          this.roles = resp.data.list;
          this.total = resp.data.total;
        }
      });
    },
    // 编辑用户提交表单
    submitEditRoleForm(ruleForm) {
      // ruleForm为添加用户的表格,不合法的话不提交
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (this.redio == 1) {
            this.ruleForm.uneffectTime = null;
          }
          this.ruleForm.status = this.redio;
          this.postRequest("/role/edit", this.ruleForm).then((resp) => {
            if (resp.data) {
              // 编辑提交后关闭弹窗初始化用户信息，重置表单
              this.addRoleFormVisible = false;
              this.initRoles();
              this.resetRuleForm();
            }
          });
        } else {
          return false;
        }
      });
    },
    //添加角色提交表单
    submitForm(ruleForm) {
      // ruleForm为添加用户的表格,不合法的话不提交
      this.$refs[ruleForm].validate((valid) => {
        let newRole = this.ruleForm;
        if (valid) {
          if (this.redio == 1) {
            //如果是有效的就把无效的设为空
            newRole.uneffectTime = null;
          }
          this.ruleForm.status = this.redio;
          this.postRequest("/role/add", newRole).then((resp) => {
            if (resp.data) {
              this.addRoleFormVisible = false;
              this.initRoles();
              this.resetForm(ruleForm);
            }
          });
        } else {
          return false;
        }
      });
    },
    //获取系统当前日期,新增角色的时候默认生效时间为当前日期
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}`;
      //  this.$set(this.searchFormField, "date", defaultDate);
      this.ruleForm.effectTime = defaultDate;
      this.ruleForm.uneffectTime = defaultDate;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.tools {
  margin-top: 10px;
}
.addRoleButton {
  margin-right: 20px;
}
</style>
